<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of soaUsers
 *
 * @author dxx
 */

namespace app\common\model\jooj_member;

use think\Model;

class MemberTags extends Model {

    protected $base_member_tags_table = 'jj_member_tags'; //标签会员关系表
    protected $base_tags_table = 'jj_tags'; //标签基础表
    protected $table = 'jj_member_tags';    //标签会员关系表
    protected $tags_table = 'jj_tags'; //标签表
    protected $company_id = null;
    protected $connection = ['database' => 'jooj_member'];

    public function __construct($company_id = []) {

        if (!is_array($company_id)) {
            //标签会员管理表
            $this->table = $this->base_member_tags_table . '_' . $company_id;
            //标签表
            $this->tags_table = $this->base_tags_table . "_" . $company_id;
        }

        parent::__construct($company_id);
    }

    /**
     * 获取公司下用户标签
     * @param type $memberCodeArr
     * @return type
     */
    public function getTags($memberCodeArr) {
        $where = ['member_code' => ['in', $memberCodeArr]];
        $res = $this->setTable($this->table)->join("{$this->tags_table}", "{$this->table}.tag_id = {$this->tags_table}.tag_id", "LEFT")
                        ->where($where)->column("{$this->tags_table}.tag_id as tagID,{$this->tags_table}.name as tagName,{$this->table}.total as tagMemCount");
        return $res;
    }

    /**
     * 添加会员标签
     */
    public function addTags($memberCodeArr, $memberCode, $tagIds) {
        //首先验证这些标签的id是否存在
        $tag_id_arr = explode(',', $tagIds);
        $have_tag_id = $this->setTable($this->tags_table)->where(['tag_id' => ['in', $tag_id_arr]])->column('tag_id');
        $diff_tag_id = array_diff($tag_id_arr, $have_tag_id);
        //如果发现有存在标签没有的，告诉他标签错误
        if (!empty($diff_tag_id)) {
            return false;
        }
        //受影响的Id
        $insertIds = [];
        //遍历判断每一个tagId是否在memberCode列表中存在，如果存在就在原有基础上+1，否则insert
        foreach ($tag_id_arr as $item) {
            $result = $this->setTable($this->table)->where(['tag_id' => $item, 'member_code' => $memberCode])->find();
            if ($result) {
                $m_tag_id = $result['m_tag_id'];
                $this->setTable($this->table)->where(['m_tag_id' => $m_tag_id])->setInc('total', 1);
                $insertIds[] = $m_tag_id;
            } else {
                $data = [
                    'member_code' => $memberCode,
                    'tag_id'      => $item,
                    'total'       => 1,
                    'last_ts'     => time()
                ];
                $id = $this->setTable($this->table)->insertGetId($data);
                $insertIds[] = $id;
            }
        }

        return implode(',', $insertIds);
    }

}
